package cfig

import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.apache.commons.exec.PumpStreamHandler
import java.io.ByteArrayOutputStream
import java.io.File

fun String.check_output(): String {
    val outputStream = ByteArrayOutputStream()
    println(this)
    DefaultExecutor().let {
        it.streamHandler = PumpStreamHandler(outputStream)
        it.execute(CommandLine.parse(this))
    }
    println(outputStream.toString().trim())
    return outputStream.toString().trim()
}

fun main(args: Array<String>) {
    val apktool = "/home/yu/.programs/plugged/apktool/bin/apktool"
    val errorApks = mutableListOf<String>()
    listOf("system", "vendor", "product", "system_ext").forEach { partitionName ->
        listOf("priv-app", "app").forEachIndexed { index, appCategory ->
            val shouldContinue = try {
                DefaultExecutor().execute(CommandLine.parse("adb shell stat /$partitionName/$appCategory/"))
                true
            } catch (e: Exception) {
                false
            }
            if (shouldContinue) {
                val apps = ("adb shell ls /$partitionName/$appCategory/").check_output()
                apps.split("\n").forEach {
                    ("incoming/" + ("${partitionName}_${appCategory}_$it".replace("-)", "_"))).let { dirName ->
                        File(dirName).mkdirs()
                        val exec = DefaultExecutor().apply {
                            workingDirectory = File(dirName)
                        }
                        exec.execute(CommandLine.parse("adb pull /$partitionName/$appCategory/$it/$it.apk"))
                        try {
                            exec.execute(CommandLine.parse("$apktool d $it.apk"))
                        } catch (e: Exception) {
                            errorApks.add("$it.apk")
                        }
                    }
                }
            }
        }
    }
    errorApks.forEach {
        println("Error apk: " + it)
    }
}

main(arrayOf())
